var port = 3000;
var log4js = require('log4js');

//配置日志信息
log4js.configure({
    appenders: [
        {type: 'console'}, {
            "type": "dateFile",
            "filename": "logs/access",
            "pattern": "-yyyy-MM-dd.log",
            "alwaysIncludePattern": true
        }
    ]
});
var logger = log4js.getLogger('normal');
logger.setLevel('INFO');
var express = require('express');
var path = require('path');
var IO = require('socket.io');

var router = express.Router();

var app = express();
var server = require('http').Server(app);
app.use(express.static(path.join(__dirname, 'public')));

// 创建socket服务
var socketIO = IO(server);
var roomInfo = {};
var roomSocket = {};
var sessionUser = {};
app.use(log4js.connectLogger(logger, {level: log4js.levels.INFO}));


socketIO.on('connection', function (socket) {
    var user = {};
    var current_roomId = "";
    var sessionId = "";
    //链接成功之后，配置用户信息
    socket.on('connectionConfig', function (roomId, uf) {
        current_roomId = roomId;
        sessionId = socket.id;
        if (!roomInfo[current_roomId]) {
            roomInfo[current_roomId] = [];
            roomSocket[current_roomId] = [];
        }
        if (typeof uf === 'function') {
            uf();
        }
    });
    //用户加入放假女同志
    socket.on('join', function (userName) {
        user = userName;
        sessionUser[sessionId] = user.userids;
        // 将用户昵称加入房间名单中
        if (!roomInfo[current_roomId]) {
            roomInfo[current_roomId] = [];
            roomSocket[current_roomId] = [];
        }
        if (typeof roomInfo[current_roomId][user.userids] != "undefined") {//如果用户已经登陆，剔除当前这个用户
            roomSocket[current_roomId][user.userids].emit("other_login", "已在其他地方登陆");
            logger.info("用户已经登陆:" + JSON.stringify(user));
        }
        roomInfo[current_roomId][user.userids] = user;
        roomSocket[current_roomId][user.userids] = socket;
        socket.join(current_roomId);    // 将当前连接加入current_roomId命名空间进行管理
        // 通知空间内的所有人员
        var userdata = {"cot": user.username + '加入了房间'};
        socketIO.to(current_roomId).emit('sys', user.username + '加入了房间', roomInfo[current_roomId], userdata, user);
        logger.info(user.username + '加入了' + current_roomId);
        logger.info("用户信息：【" + JSON.stringify(user) + "】");

    });

    socket.on('leave', function () {
        logger.info("用户【" + [user.userids] + "】已经离开之前的处理");
        socket.emit('disconnect');
    });

    socket.on('disconnect', function () {
        logger.info("准备移除用户【" + [user.userids] + "】");
        // 从房间名单中移除
        if (typeof roomInfo[current_roomId] === "undefined") {
            return false;
        }
        var obj = roomInfo[current_roomId][user.userids];
        if (typeof obj != "undefined") {
            delete(roomInfo[current_roomId][user.userids]);
            delete(roomSocket[current_roomId][user.userids]);
        }

        socket.leave(current_roomId);    // 退出房间
        var msg_tmp = {"msg": user.username + '退出了房间', "type": "disconnect"};
        socketIO.to(current_roomId).emit("notice", user, msg_tmp, user);
        var sys_exit_msg = {"cot": user.username + '退出出了房间'};
        logger.info(JSON.stringify(user) + '退出了' + current_roomId, sys_exit_msg);
    });

    // 接收用户消息,发送相应的房间
    socket.on('message', function (msg) {
        if (!check_user_in_room(current_roomId, user)) {
            return false;
        }
        logger.info(JSON.stringify(msg));

        var user = roomInfo[current_roomId][user.userids];

        if (user.forbidden == true) {
            return false;
        }

        if (!msg.msg.type) {//普通消息
            socketIO.to(current_roomId).emit('msg', msg);
        } else {
            switch (msg.msg.type) {
                case "advance"://高级消息
                    if (user.vip && user.vip == true) {//验证是否为高级用户
                        socketIO.to(current_roomId).emit('msg_advance', user, msg);
                    } else {//没有权限时发送通知
                        logger.info("用户ID没有发送高级消息的权限");
                        socketIO.to(current_roomId).emit('authError', '您没有权限', '1', msg);
                    }
                    break;
            }
        }
    });
    //用户禁言
    socket.on("forbidden", function (forbidden_user) {
        if (check_fobidden_auth(user)) {
            var msg = {"type": "forbidden_access_none", "msg": "您的权限不够"};
            socket.emit("notice", user, msg);
            if (check_user_in_room(current_roomId, user)) {
                var _user = roomInfo[current_roomId][forbidden_user.userids];
                _user.forbidden = true;
                roomInfo[current_roomId][forbidden_user.userids] = _user;
                ////更新用户
                //roomInfo[current_roomId].splice(index,1,user);
            }
            logger.info("用户被禁言【" + JSON.stringify(forbidden_user) + "】");
        } else {//禁言用户
            logger.info("用户禁言权限不够【" + JSON.stringify(user) + "】");
            socketIO.to(current_roomId).emit("notice", forbidden_user);
        }
    });

    //提出用户
    socket.on("user_out", function (out_user) {
        if (check_out_auth(user)) {
            var msg = {"type": "userout_access_none", "msg": "您的权限不够"};
            logger.info("用户被提出房间【用户信息：" + JSON.stringify(out_user) + "，房间号：" + current_roomId + "】");
            socket.emit("", user, msg);
        } else {
            logger.info("用户踢人权限不够【" + JSON.stringify(user) + "】");
            socketIO.to(current_roomId).emit("notice", out_user);
        }
    });
    //用户开通vip
    socket.on("buy_vip", function (user, fid, msg) {
        logger.info("用户开通VIP功能");
        if (!check_user_in_room(fid, user)) {
            logger.info(JSON.stringify(user));
            return false;
        }
        logger.info("找到了用户的信息,准备下发通知信息" + JSON.stringify(user));
        socketIO.to(fid).emit("notice", user, msg);
    });
});
/**
 * 检测用户是否拥有禁言权限
 * @param user
 * @returns {boolean}
 */
function check_fobidden_auth(user) {
    if (check_auth()) {
        return true;
    }
    return false;
}
/**
 * 判断用户是否拥有踢人的权限
 * @param user
 * @returns {boolean}
 */
function check_out_auth(user) {
    if (check_auth()) {
        return true;
    }
    return false;
}

/**
 * 判断用户权限
 * @param user
 * @returns {boolean}
 */
function check_auth(user) {
    //if (user.adminid == 1 || user.adminid == 2) {
    return true;
    //}
    //return false;
}

//验证用户是否在房间内
function check_user_in_room(roomId, user) {
    if (typeof roomInfo[roomId] === "undefined") {
        return false;
    }
    // 验证如果用户不在房间内则不给发送
    var index = roomInfo[roomId][user.userids];
    if (typeof index === "undefined") {
        return false;
    }
    return true;
}

app.use('/', router);
server.listen(port, function () {
    logger.info('server listening on port ' + port);
});
